package com.manli.api.service;


import com.manli.api.base.exception.MyException;
import com.manli.api.dao.*;
import com.manli.api.dto.*;
import com.manli.api.enums.ResultEnums;
import com.manli.api.pojo.PermissionVue;
import com.manli.api.pojo.SessionInfo;
import com.manli.api.pojo.UserPermission;
import com.manli.api.util.DruidUtils;
import com.manli.api.util.SessionInfoUtils;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class UserPermissionService {
	
	@Autowired
	UserPermissionDao userPermissionDao;
	@Autowired
	UserPermissionVueDao userPermissionVueDao;
	@Autowired
	UserDao userDao;
	@Autowired
	RoleDao roleDao;
	@Autowired
	PermissionDao permissionDao;
	@Autowired
	RolePermissionDao rolePermissionDao;
	@Autowired
	UserRoleDao userRoleDao;
	@Autowired
	SessionInfoUtils sessionInfoUtils;
	
	/**
	 *  ！！！！！！此处修改 同步修改下面 getUserPermission！！！！！！
	 *  
	 * @param userId
	 * @param request
	 * @return
	 */
	public List<UserPermission> getUserPermission(Integer userId,HttpServletRequest request) {
		SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
		String sql = 
				"SELECT " + 
				"  u.user_id as userId, " + 
				"  u.username, " + 
				"  r.role_name as roleName, " + 
				"  p.permission_id as permissionId, " + 
				"  p.permission, " + 
				"  p.permission_name as permissionName, " + 
				"  p.permission_parent as permissionParent, " + 
				"  p.permission_type as permissionType " + 
				"FROM `user` u " + 
				"LEFT JOIN user_role ur on u.user_id = ur.user_id " + 
				"LEFT JOIN role r on ur.role_id = r.role_id " + 
				"LEFT JOIN role_permission rp on rp.role_id= r.role_id " + 
				"LEFT JOIN permission p on p.permission_id = rp.permission_id " + 
				"where u.user_id = ? "+
				"and u.status = 1 "+
				"and p.status=1 "+
				"and r.status=1 ";
		if(sessionInfo.getBranchId() != 1) {
			sql+="and IFNULL(p.branch_id,0)!=1 ";
		}
		return userPermissionDao.execute(sql, userId);
	}
	/**
	 *   ！！！！！！此处修改 同步修改上面 getUserPermission！！！！！！
	 * @param userId
	 * @param branchId
	 * @return
	 */
	public List<UserPermission> getUserPermission(Integer userId,Integer branchId) {
		String sql = 
				"SELECT " + 
				"  u.user_id as userId, " + 
				"  u.username, " + 
				"  r.role_name as roleName, " + 
				"  p.permission_id as permissionId, " + 
				"  p.permission, " + 
				"  p.permission_name as permissionName, " + 
				"  p.permission_parent as permissionParent, " + 
				"  p.permission_type as permissionType " + 
				"FROM `user` u " + 
				"LEFT JOIN user_role ur on u.user_id = ur.user_id " + 
				"LEFT JOIN role r on ur.role_id = r.role_id " + 
				"LEFT JOIN role_permission rp on rp.role_id= r.role_id " + 
				"LEFT JOIN permission p on p.permission_id = rp.permission_id " + 
				"where u.user_id = ? "+
				"and u.status = 1 "+
				"and p.status=1 "+
				"and r.status=1 ";
		if(branchId != 1) {
			sql+="and IFNULL(p.branch_id,0)!=1 ";
		}
		return userPermissionDao.execute(sql, userId);
	}

	public List<PermissionVue> getUserPermissionVue(Integer userId , Integer branchId) {
		String sql =
				"SELECT " +
						" c.permission_id, " +
						" c.permission path, " +
						" c.permission_name name, " +
						" c.icon, " +
						" c.component, " +
						" c.permission_parent, " +
						" c.auth_require,  " +
						" c.is_menu  " +
						"FROM " +
						" user_role a " +
						" LEFT JOIN role_permission b ON a.role_id = b.role_id " +
						" LEFT JOIN permission c ON b.permission_id = c.permission_id  " +
						"WHERE " +
						" c.permission_type = 1 "+ 
						"and a.user_id = ? " ; 
				if(branchId!=1) {
					sql+="and IFNULL(c.branch_id,0) != 1 ";
				}		
				sql+="order by c.sort ";
		List<PermissionVue> list = userPermissionVueDao.execute(sql, userId);
		list.forEach(permissionVue -> {
			List<PermissionVue> clist = new ArrayList<>();
			list.forEach(permissionVue1 -> {
				if(permissionVue1.getPermissionParent().intValue() != 0 && permissionVue1.getPermissionParent().intValue() == permissionVue.getPermissionId().intValue()){
					clist.add(permissionVue1);
				}
			});
			permissionVue.setChildren(clist);

			if(permissionVue.getAuthRequire().intValue() == 1){
				Map map = new HashMap();
				map.put("requireAuth",true);
				permissionVue.setMeta(map);
			}
		});
		list.removeIf(permissionVue2 -> permissionVue2.getPermissionParent().intValue() != 0);
		return list;
	}
	@Transactional
	public void saveUser(User user) {
		if (userDao.templateOne(user) != null) {
			throw new MyException(ResultEnums.USER_EXIT);
		}
		user.setStatus(1);//默认启用 
		userDao.insert(user);
	}
	@Transactional
	public void saveRole(Role role) {
		roleDao.insert(role);
	}
	@Transactional
	public void savePermission(Permission permission) {
		permissionDao.insert(permission);
	}
	@Transactional
	public void saveRolePermission(List<RolePermission> rolePermissions) {
		//先删除原来角色的所有权限
		rolePermissionDao.executeUpdate("delete from role_permission where role_id=?",rolePermissions.get(0).getRoleId());
		//保存新的角色权限
		rolePermissionDao.insertBatch(rolePermissions);
	}
	@Transactional
	public void saveUserRoles(List<UserRole> userRoles) {
		//先删除原来用户所有的所有角色
		userRoleDao.executeUpdate("delete from user_role where user_id=? ", userRoles.get(0).getUserId());
		//保存新的用户角色
		userRoleDao.insertBatch(userRoles);
	}
	@Transactional
	public void updateUser(User user) {
		userDao.updateTemplateById(user);
	}
	@Transactional
	public void updateRole(Role role) {
		roleDao.updateTemplateById(role);
	}
	@Transactional
	public void updatePermission(Permission permission) {
		permissionDao.updateTemplateById(permission);
	}

	/**
	 * 通过用户名密码或则用户信息
	 * @param name
	 * @param password
	 * @return
	 */
	public User getUserByNameAndPasswd(String name, String password ,String loginBranchPartnerName) throws Exception{
		password = DruidUtils.generateEncryptPassword(password);
		String sql = 
				"select "
				+ "u.user_id as userId,"
				+ "u.username,"
				+ "u.user_phone userPhone,"
				+ "b.branch_id as branchId,"
				+ "p.partner_id as partnerId,"
				+ "b.branch_name as branchName,"
				+ "p.partner_name as partnerName "
				+ "from user u  "
				+ "left join branch b on u.branch_id = b.branch_id "
				+ "left join partner p on b.branch_id = p.branch_id "
				+ "where username=? "
				+ "and password=? "
				+ "and (b.branch_name = ? or p.partner_name = ? ) "
				+ "and u.status = 1 "
				+ "and b.status = 1 "
				+ "and IFNULL(p.status,1) = 1 ";
		List<User> user = userDao.execute(sql, name , password , loginBranchPartnerName , loginBranchPartnerName);
		if(user.size()>0) {
			return user.get(0);
		}
		return null;
	}

	/**
	 * 通过用户名密码或则用户信息
	 * @param name
	 * @param password
	 * @return
	 */
	public User getUserAndPasswd(String name, String password ) throws Exception{
		password = DruidUtils.generateEncryptPassword(password);
		String sql =
				"select "
						+ "u.user_id as userId,"
						+ "u.username,"
						+ "u.user_phone userPhone,"
						+ "b.branch_id as branchId,"
						+ "p.partner_id as partnerId,"
						+ "b.branch_name as branchName,"
						+ "p.partner_name as partnerName "
						+ "from user u  "
						+ "left join branch b on u.branch_id = b.branch_id "
						+ "left join partner p on u.partner_id = p.partner_id "
						+ "where username=? "
						+ "and password=? "
						+ "and u.status = 1 "
						+ "and b.status = 1 "
						+ "and IFNULL(p.status,1) = 1 ";
		List<User> user = userDao.execute(sql, name , password);
		if(user.size()>0) {
			return user.get(0);
		}
		return null;
	}

	/**
	 * 通过用户ID获取用户信息
	 * @return
	 */
	public User getUserByUserId(Integer userId ) throws Exception{
		String sql =
				"select "
						+ "u.user_id as userId,"
						+ "u.username,"
						+ "u.user_phone userPhone,"
						+ "b.branch_id as branchId,"
						+ "p.partner_id as partnerId,"
						+ "b.branch_name as branchName,"
						+ "p.partner_name as partnerName "
						+ "from user u  "
						+ "left join branch b on u.branch_id = b.branch_id "
						+ "left join partner p on b.branch_id = p.branch_id "
						+ "where 1=1 "
						+ "and u.user_id=? "
						+ "and u.status = 1 "
						+ "and b.status = 1 "
						+ "and IFNULL(p.status,1) = 1 ";
		List<User> user = userDao.execute(sql, userId);
		if(user.size()>0) {
			return user.get(0);
		}
		return null;
	}
	
}
